package com.study.common.utils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author: 王霄
 * @date: 2021/9/12 14:03
 */
public class DateUtil {

    /**
     * 默认时区
     */
    private static final ZoneOffset zoneOffset = ZoneOffset.ofHours(8);

    /**
     * 默认时间格式化器
     */
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static String format(LocalDateTime dateTime) {
        return formatter.format(dateTime);
    }

    public static String format(Date date) {
        return format(toLocalDateTime(date));
    }

    public static String format(long millisecond) {
        return format(Instant.ofEpochMilli(millisecond).atOffset(zoneOffset).toLocalDateTime());
    }

    public static LocalDateTime parseLocalDateTime(String str) {
        return LocalDateTime.parse(str, formatter);
    }

    public static Instant parseInstant(String str) {
        return parseLocalDateTime(str).toInstant(zoneOffset);
    }

    public static Date toDate(LocalDateTime dateTime) {
        return Date.from(dateTime.toInstant(zoneOffset));
    }

    public static Date toDate(LocalDate localDate) {
        return toDate(localDate.atStartOfDay());
    }

    public static LocalDateTime toLocalDateTime(Date date) {
        return date.toInstant().atOffset(zoneOffset).toLocalDateTime();
    }

    public static LocalDate toLocalDate(Date date) {
        return toLocalDateTime(date).toLocalDate();
    }

    public static LocalDateTime toLocalDateTime(long timestamp) {
        return Instant.ofEpochMilli(timestamp).atOffset(zoneOffset).toLocalDateTime();
    }

    public static LocalDate toLocalDate(long timestamp) {
        return toLocalDateTime(timestamp).toLocalDate();
    }

    public static long toTimestamp(LocalDate localDate) {
        return toTimestamp(localDate.atStartOfDay());
    }

    public static long toTimestamp(LocalDateTime localDateTime) {
        return localDateTime.toInstant(zoneOffset).toEpochMilli();
    }
}
